# uncompyle6 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
# Embedded file name: C:\Users\myh\Desktop\juqi\juqidjango\juqidjango\juqi_server\quanjushang\ser.py
# Compiled at: 2023-02-06 17:02:41
# Size of source mod 2**32: 965 bytes
from rest_framework import serializers
from .models import (
    QuanjushangGame,
    QuanjushangSonGame,
    QuanjushangRecord,
    QuanjushangGood,
    QuanjushangBindMethod,
)

from jqgame.basegame import GameType
from warehouse.models import JuqiGood, GoodLevel
from wxuser.models import UserPackage, UserPackageRecord, Users
from django.db.models import Sum
import pandas as pd
from jqpackage.models import UserPackageGoods
from wxuser.models import UserOrder
from warehouse.serializers import JuqiGoodSerializer


class WxuserSer(serializers.ModelSerializer):
    class Meta:
        model = Users
        fields = ("nickname", "head_url")


class JuqigoodSer(serializers.ModelSerializer):
    class Meta:
        model = JuqiGood
        fields = ("name", "display_url", "price", "recovery_price")


class QuanjushangGameSerializer(serializers.ModelSerializer):
    createdAt = serializers.DateTimeField(
        format="%Y-%m-%d %H:%M:%S", required=False, read_only=True
    )

    class Meta:
        model = QuanjushangGame
        fields = ("uuid", "createdAt", "name", "cover_url", "price")


class QuanjushangGamSer(serializers.ModelSerializer):
    createdAt = serializers.DateTimeField(
        format="%Y-%m-%d %H:%M:%S", required=False, read_only=True
    )

    class Meta:
        model = QuanjushangGame
        fields = "__all__"


class QuanjushangGoodSerializer(serializers.ModelSerializer):
    detail = serializers.SerializerMethodField()
    good_level_uuid = serializers.SerializerMethodField()

    class Meta:
        model = QuanjushangGood
        fields = "__all__"

    def get_detail(self, obj):
        return JuqiGoodSerializer(
            JuqiGood.objects.filter(uuid=obj.good_uuid).first(), many=False
        ).data

    def get_good_level_uuid(self, obj):
        good_level = GoodLevel.objects.filter(title=obj.good_title).first()
        return good_level.uuid


class XcxQjsOneInfo(serializers.ModelSerializer):
    rfcount = serializers.SerializerMethodField()

    class Meta:
        model = QuanjushangSonGame
        fields = "__all__"

    def get_rfcount(self, obj):
        rf_count = (
            QuanjushangGood.objects.filter(son_uuid=obj.uuid)
            .filter(deleted=False)
            .filter(good_type=0)
            .aggregate(Sum("rf_count"), Sum("count"))
        )
        return rf_count


class QuanjushangSonGameSerializer(serializers.ModelSerializer):
    rfcount = serializers.SerializerMethodField()

    class Meta:
        model = QuanjushangSonGame
        fields = "__all__"

    def get_rfcount(self, obj):
        rf_count = (
            QuanjushangGood.objects.filter(son_uuid=obj.uuid)
            .filter(deleted=False)
            .filter(good_type=0)
            .aggregate(Sum("rf_count"), Sum("count"))
        )
        return rf_count


class QuanjushangGameAdminSerializer(serializers.ModelSerializer):
    """
    管理员主页查看全局赏list
    """

    method_list = serializers.SerializerMethodField()

    class Meta:
        model = QuanjushangGame
        fields = ("uuid", "createdAt", "name", "cover_url")


class QjsGoosinGameser(serializers.ModelSerializer):
    """
    全局赏池子下的赏品
    """

    createdAt = serializers.DateTimeField(
        format="%Y-%m-%d %H:%M:%S", required=False, read_only=True
    )

    class Meta:
        model = QuanjushangGood
        fields = (
            "createdAt",
            "uuid",
            "count",
            "good_uuid",
            "good_title",
            "good_name",
            "good_desc",
            "good_url",
            "good_descurl",
            "price",
            "recovery_price",
            "good_type",
            "count",
        )


class QjsRecordser(serializers.ModelSerializer):
    """
    中奖记录
    """

    createdAt = serializers.DateTimeField(
        format="%Y-%m-%d %H:%M:%S", required=False, read_only=True
    )
    user_info = serializers.SerializerMethodField()
    good_info = serializers.SerializerMethodField()

    class Meta:
        model = QuanjushangRecord
        fields = "__all__"

    def get_user_info(self, obj):
        user = Users.objects.filter(uuid=obj.user_uuid).first()
        return WxuserSer(user, many=False).data

    def get_good_info(self, obj):
        good = JuqiGood.objects.filter(uuid=obj.good_uuid).first()
        return JuqigoodSer(good, many=False).data


def save_UserPackages(
    infos,
    game_type: GameType,
):
    wxsrrs_create = []
    page_create = []

    def _save_UserPackage(infoc):
        info = {
            "user_uuid": infoc["user_uuid"],
            "good_uuid": infoc["good_uuid"],
            "game_uuid": infoc["game_uuid"],
            "songame_uuid": infoc["game_son_uuid"],
            "seat_number": infoc["order_num"],
            "deleted": False,
        }

        if infoc.get("order_uuid"):
            infoc["order_uuid"] = infoc["order_uuid"]
        else:
            zhong_user_order = (
                UserOrder.objects.filter(deleted=False)
                .filter(game_type=GameType.quanjushang.value)
                .filter(user_uuid=infoc["user_uuid"])
                .filter(game_uuid=infoc["game_uuid"])
                .filter(son_uuid=infoc["game_son_uuid"])
                .filter(box_num=infoc["game_box_num"])
                .first()
            )
            infoc["order_uuid"] = zhong_user_order.uuid

        infoc["game_type"] = GameType.quanjushang.value

        if game_type == GameType.quanjushang:
            wxsrrs_create.append(QuanjushangRecord(**info))
            page_create.append(UserPackageGoods(**infoc))

    for i in infos:
        _save_UserPackage(i)

    UserPackageGoods.objects.bulk_create(page_create, batch_size=1000)

    if game_type == GameType.quanjushang:
        QuanjushangRecord.objects.bulk_create(wxsrrs_create, batch_size=1000)


def Percentage_calculation(num: dict):
    shu_num = []
    for item, value in num.items():
        shu_num.append(value)

    df = pd.DataFrame(shu_num)

    m = df / df.sum()
    m = m.values

    baifen_list = []
    for i in m:
        a = str(round(i[0] * 100, 2)) + "%"
        baifen_list.append(a)

    _num = 0
    for item, value in num.items():
        num[item] = baifen_list[_num]
        _num += 1

    # 最大下标key
    max_key = ""
    # 加一起数值
    count_num = 0.00

    for item, value in num.items():
        if max_key == "":
            max_key = item
        else:
            if float(str(num[item]).replace("%", "")) > float(
                str(num[max_key]).replace("%", "")
            ):
                max_key = item
        count_num += float(str(num[item]).replace("%", ""))

    if count_num < 100.00:
        difference = round(100.00 - count_num, 2)
        count_num += difference
        jine = float(str(num[max_key]).replace("%", "")) + difference
        num[max_key] = str(round(jine,2)) + "%"

    if count_num > 100.00:
        difference = round(count_num - 100.00, 2)
        count_num -= difference
        jine = float(str(num[max_key]).replace("%", "")) - difference
        num[max_key] = str(round(jine,2)) + "%"

    return num
